#!/usr/bin/perl

use strict;
use warnings;

use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use DBI;
use POSIX;

use FindBin qw($Bin);
use lib "$Bin";

use open_flash_chart;

my $db_host="mentok.atnf.csiro.au";
my $db_port=5432;
my $html_host=$db_host;
my $html_port=8080;

my $dsn="dbi:Pg:dbname=atca;host=$db_host;port=$db_port";
my $user="postgres";
my $password="";

my $buffer;

open(OUT,">/tmp/output.txt");

# read in the parameters
$ENV{'REQUEST_METHOD'}=~tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "GET"){
    $buffer=$ENV{'QUERY_STRING'};
}
# split information into name/value pairs
my @pairs=split(/\&/,$buffer);
my %FORM;
foreach my $pair (@pairs) {
    my ($name,$value)=split(/\=/,$pair);
    $value=~tr/+/ /;
    $value=~s/%(..)/pack("C",hex($1))/eg;
    $FORM{$name}=$value;
}

print OUT $FORM{'data'}."\n";
($FORM{'source'},$FORM{'freq'})=split("_",$FORM{'data'});

print header('application/json');
#print header;

my $dbh=DBI->connect($dsn,$user,$password,{RaiseError => 0,
					   AutoCommit => 1});

my @get_columns=("fluxdata.data_freq","fluxdata.tripleamp_value",
		 "fluxdata.tripleamp_scatter_measured","observation.time");
my %query_columns;
my $gdt_query_restrictions="observation.id=any(fluxdata.observation_ids) AND fluxdata.frequency=".
    $FORM{'freq'}." AND fluxdata.source='".$FORM{'source'}."'".
    " AND fluxdata.quality_flag=true";
my $gdt_query="SELECT ";
for (my $i=0;$i<=$#get_columns;$i++){
    $query_columns{$get_columns[$i]}=$i;
    if ($i!=0){
	$gdt_query.=",";
    }
    $gdt_query.=$get_columns[$i];
}
$gdt_query.=" FROM fluxdata,observation WHERE ".$gdt_query_restrictions;
print OUT "$gdt_query<br />\n";
close OUT;

my $gdt=$dbh->prepare($gdt_query);
$gdt->execute;


my %datapoints;
while (my @response=$gdt->fetchrow()){
    my @thesefreqs=@{$response[$query_columns{'fluxdata.data_freq'}]};
    my @thesefluxes=@{$response[$query_columns{'fluxdata.tripleamp_value'}]};
    my @theseflux_errors=@{$response[$query_columns{'fluxdata.tripleamp_scatter_measured'}]};
    for (my $i=0;$i<=$#thesefreqs;$i++){
	my $thisfreq1=ceil($thesefreqs[$i]*1000.0);
	my $thisfreq2=floor($thesefreqs[$i]*1000.0);
	if (($thisfreq1==$FORM{'freq'})||($thisfreq2==$FORM{'freq'})){
	    push @{$datapoints{"flux_$thesefreqs[$i]"}},$thesefluxes[$i];
	    push @{$datapoints{"fluxerr_$thesefreqs[$i]"}},$theseflux_errors[$i];
	    push @{$datapoints{"time_$thesefreqs[$i]"}},
	    &time_to_unixtime($response[$query_columns{'observation.time'}]);
	    my @allfrequencies;
	    if ($datapoints{'frequencies'}){
		@allfrequencies=@{$datapoints{'frequencies'}};
	    }
	    my $foundfreq=0;
	    for (my $j=0;$j<=$#allfrequencies;$j++){
		if ($thesefreqs[$i]==$allfrequencies[$j]){
		    $foundfreq=1;
		    last;
		}
	    }
	    if ($foundfreq==0){
		push @{$datapoints{'frequencies'}},$thesefreqs[$i];
	    }
	}
    }
}
$gdt->finish;

$dbh->disconnect;

# ok make the JSON file now
my $json_text="{";
# title
$json_text.="\"title\":{";
my @allfrequencies;
if ($datapoints{'frequencies'}){
    @allfrequencies=@{$datapoints{'frequencies'}};
}
$json_text.="\"text\":\"".$FORM{'source'}." \@ ".$FORM{'freq'}." GHz\"";
$json_text.=",\"style\":\"font-size: 14px; font-family: Verdana; text-align: center;\"}";
$json_text.=", \"x_axis\":{";
#$json_text.="\"steps\":604800";
#$json_text.="\"steps\":1209600";
$json_text.="\"steps\":2419200";
my ($mintime,$maxtime)=&minmax(@{$datapoints{"time_$allfrequencies[0]"}});
$json_text.=",\"min\":".$mintime;
$json_text.=",\"max\":".$maxtime;
$json_text.=",\"labels\":{";
$json_text.="\"text\":\"#date#\",\"steps\":2419200,\"visible-steps\":1}";
$json_text.="}";
$json_text.=", \"y_axis\":{";
$json_text.="\"steps\":1";
my ($minflux,$maxflux)=&minmax(@{$datapoints{"flux_$allfrequencies[0]"}});
$json_text.=",\"min\":".$minflux;
$json_text.=",\"max\":".$maxflux;
$json_text.="}";
$json_text.=",\"tooltip\":{\"mouse\":1}";
#$json_text.=",\"y_legend\":{\"text\":\"Flux (Jy)\"}";
$json_text.=", \"bg_colour\":\"#ffffff\"";
$json_text.=",\"elements\":[{";
$json_text.="\"type\":\"scatter\",\"colour\":\"#000000\"";
$json_text.=",\"dot-style\":{";
$json_text.="\"type\":\"hollow-dot\",\"colour\":\"#111111\",\"dot-size\":4}";
$json_text.=",\"values\":[";
my @fluxes=@{$datapoints{"flux_$allfrequencies[0]"}};
my @fluxerrs=@{$datapoints{"fluxerr_$allfrequencies[0]"}};
my @times=@{$datapoints{"time_$allfrequencies[0]"}};
for (my $i=0;$i<=$#fluxes;$i++){
    if ($i>0){
	$json_text.=",";
    }
    $json_text.="{\"x\":".$times[$i].",\"y\":".$fluxes[$i].",".
	"\"tip\":\"#date:Y-m-d H:i:s#\nFlux: #y# +/- ".
	$fluxerrs[$i]." Jy\"}";
}
$json_text.="]}]";
$json_text.="}";

print "$json_text\n";


sub minmax {
    my @array=@_;
    
    my $minval=$array[0];
    my $maxval=$array[0];

    for (my $i=0;$i<=$#array;$i++){
	if ($array[$i]<$minval){
	    $minval=$array[$i];
	}
	if ($array[$i]>$maxval){
	    $maxval=$array[$i];
	}
    }

    return ($minval,$maxval);
}

sub time_to_unixtime {
    my ($ptime)=@_;
    
    $ptime=~/^(\d{4})\-(\d{2})\-(\d{2})\s(\d{2})\:(\d{2})\:(\d{2})/;
    my ($year,$month,$day,$hour,$minute,$second)=($1,$2,$3,$4,$5,$6);
    $year-=1900;
    $month-=1;

    my $utime=mktime($second,$minute,$hour,$day,$month,$year,0,0);

    return $utime;
}

sub text_to_array {
    my ($string)=@_;

    $string=~s/[\{\}]//g;
    my @els=split(/\,/,$string);

    return @els;
}

sub round {
    my($number) = shift;
    return int($number + .5);
}
